const request = require("request")
const cheerio = require("cheerio")
const weatherURL = 'https://tianqi.moji.com/weather/china/Anhui/chaohu'
// const weatherURL = 'https://tianqi.moji.com/weather/china/Anhui/wuwei'

// 获取墨迹天气提示信息
function getWeatherTips(url) {
    return new Promise((resolve, reject) => {
        request(weatherURL, (error, res, body) => {
            if (!error) {
                let html = res.body || "";
                let $ = cheerio.load(html)
                let city = "巢湖"
                let temp = $('.wea_weather em').text().trim() + '℃'
                let desc = $('.wea_weather b').text().trim()
                let water = $('.wea_about span').text().trim()
                let win = $('.wea_about em').text().trim()
                let tips = $('.wea_tips em').text().trim()
                let words = `<h2>今日${city}天气\n${desc}\n温度：${temp}\n湿度：${water}\n风力：${win}\n${tips}</h2>`
                resolve(words)
            } else {
                reject(error)
            }
        })
    })
}

const greetingURL = 'http://wufazhuce.com/'
// 获取wufazhuce.com每日一句
function getDailyGreeting() {
    return new Promise((resolve, reject) => {
        request(greetingURL, (error, res, body) => {
            let everyDayWordsList = [];
            if (!error && res.statusCode == 200) {
                let $ = cheerio.load(res.body.toString())
                $('div .fp-one-cita a').each(function (item) {
                    if ($(this).text()) {
                        everyDayWordsList.push($(this).text().trim())
                    }
                })
                let result = everyDayWordsList[0] || '网络错误，获取每日问候失败！'
                result = "<h1>"+result+"</h1>"
                resolve(result)
            } else {
                reject(error)
            }
        })
    })
}

var express = require('express');
var app = express();
// const api = require('./weather')
app.get('/', async function (req, res) {
    //  let dateTips = api.getDiffDate()
    let weather = await getWeatherTips()
    let words = await getDailyGreeting()
    let str = `${weather}\n${words}`
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' })
    res.end(str)
})
var server = app.listen(8083, " 172.24.40.152", function () { // 启动ip和端口
    var port = server.address().port
    console.log("应用实例，访问地址为 http://%s:%s", port)
})
